//
//  ORCodeController.m
//  OCDemo
//
//  Created by BH on 15/10/27.
//  Copyright © 2015年 baohan. All rights reserved.
//

#import "ORCodeController.h"
#import "QRCodeGenerator.h"
#import <ZBarSDK/ZBarSDK.h>
#import <Masonry/Masonry.h>

@interface ORCodeController ()<ZBarReaderViewDelegate>
{
    ZBarReaderView *readerV;
}
@property (weak, nonatomic) IBOutlet UITextField *textF;
@property (weak, nonatomic) IBOutlet UIImageView *imageV;

@end

@implementation ORCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)createCode:(id)sender {
    //字符串生成二维码
    _imageV.image = [QRCodeGenerator qrImageForString:_textF.text imageSize:_imageV.bounds.size.width];
}

- (IBAction)Scanning:(id)sender {
    readerV = [[ZBarReaderView alloc] init];
    readerV.readerDelegate = self;
    readerV.torchMode = 0; //关闭闪光灯
    [self.view addSubview:readerV];
    
    [readerV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imageV.mas_left);
        make.top.equalTo(self.imageV.mas_bottom).offset(5);
        make.width.height.equalTo(@(self.imageV.frame.size.width-20));
    }];
    
    //扫描区域
//    CGRect scanMask = CGRectMake(60, CGRectGetMidY(readerV.frame)-126, 200, 200);
    
    //处理模拟器
    if (TARGET_IPHONE_SIMULATOR) {
        ZBarCameraSimulator *cameraSimulator = [[ZBarCameraSimulator alloc] initWithViewController:self];
        cameraSimulator.readerView = readerV;
    }
    
    //计算扫描区域
    readerV.scanCrop = readerV.bounds;//[self getScanCrop:readerV.frame readerViewBounds:readerV.bounds];

    [readerV start];  //开始扫描
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds{

    CGFloat x,y,w,h;
    
    x = rect.origin.x/readerViewBounds.size.width;
    y = rect.origin.y/readerViewBounds.size.height;
    w = rect.size.width/readerViewBounds.size.width;
    h = rect.size.height/readerViewBounds.size.height;
    
    return CGRectMake(x, y, w, h);
}

#pragma mark - ZBarReaderViewDelegate
-(void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{
    for (ZBarSymbol *sym in symbols) {
        _textF.text = sym.data;
        break;
    }
    
    [readerV stop];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [_textF resignFirstResponder];
}


@end
